﻿using Ec_System.Models.Web;
using Ec_System.Service.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace Ec_System.Bll.Web
{
    public class ShopCartManager
    {
        ShopCartService shopCartService = new ShopCartService();


        /// <summary>
        /// 预结算, 遍历购物车检查库存情况
        /// </summary>
        /// <param name="cartList"></param>
        /// <returns></returns>
        public List<ShopCartData> PreCheckOut(List<ShopCartData> cartList)
        {
            foreach(var cart  in cartList)
            {
                var itemStore = shopCartService.GetStoreByItemNumber(cart.ItemNumber, cart.VendorNumber);
                if( itemStore - cart.ProductQty  <= 0 )
                {
                    cart.StoreStatus = 0;
                }
            }

            return cartList;
        }

        /// <summary>
        /// 正式结算--订单入库
        /// </summary>
        /// <param name="cartList"></param>
        /// <param name="values"></param>
        /// <returns>0--入库失败, other -- 入库成功</returns>
        public string CheckOut(List<ShopCartData> cartList, List<KeyValuePair<string, string>> values)
        {
            MaxValueService maxValueService = new MaxValueService();
            SiteConfigManager siteConfigManager = new SiteConfigManager();
            //计算基准时间,用于生产订单
            DateTime baseTime = new DateTime(2017, 1, 1, 0, 0, 0);
            double timeSpan = Math.Floor(DateTime.Now.Subtract(baseTime).TotalSeconds);
            //计算订单的总金额
            decimal totalMoney = cartList.Sum(c => c.RowMoney);
            //获取免邮费标准
            decimal shipFreePrice = decimal.Parse( siteConfigManager.GetSiteConfigByKey("Ship_free_Price") );
            //获取运费
            decimal shipPrice = decimal.Parse(siteConfigManager.GetSiteConfigByKey("Ship_Price"));
            List<ItemOrderData> orderList = new List<ItemOrderData>();

            //分订单, 一个vendor一条订单
            var vendorList = (from vender in cartList select new { VendorNumber = vender.VendorNumber }).Distinct();
            foreach (var vendor in vendorList)
            {
                ItemOrderData order = new ItemOrderData();
                order.Discount = 1;
                order.TotalMoney = totalMoney;//总金额
                order.FactMoney = totalMoney > shipFreePrice ? totalMoney : totalMoney + shipPrice;//实付金额
                order.LoginId = values.Where(item => item.Key == "loginID").FirstOrDefault().Value;
                //生产订单号
                order.OrderId = vendor.VendorNumber + maxValueService.GetMaxValueByBiztype("SHOPOrderID" + vendor.VendorNumber, "网店销售订单号");
                order.OrderStatus = 1;
                order.PaymentType = values.Where(item => item.Key == "PayID").FirstOrDefault().Value; ;
                order.ReturnMoney = 0;
                order.ShippingType = int.Parse(values.Where(item => item.Key == "shipType").FirstOrDefault().Value);
                order.VendorNumber = vendor.VendorNumber;
                order.PaymentType = values.Where(item => item.Key == "payID").FirstOrDefault().Value;
                order.Address = values.Where(item => item.Key == "adrID").FirstOrDefault().Value;

                int detailID = 1;
                
                foreach(var cart in cartList)
                {
                    if(vendor.VendorNumber == cart.VendorNumber)
                    {
                        ItemOrderDetailsData orderDetails = new ItemOrderDetailsData();
                        orderDetails.ItemNumber = cart.ItemNumber;
                        //生产订单明细号
                        orderDetails.OrderDetailId = order.OrderId + detailID.ToString().PadLeft(3, '0');
                        orderDetails.OrderId = order.OrderId;
                        orderDetails.ProductID = cart.ProductID;
                        //生产溯源码
                        orderDetails.QRCode = vendor.VendorNumber + 1 + timeSpan + detailID.ToString().PadLeft(3, '0');
                        orderDetails.ReturnMark = 0;
                        orderDetails.Unit = cart.Unit;
                        orderDetails.UnitPrice = cart.ProductPrice;
                        orderDetails.Count = cart.ProductQty;
                        //添加到父级
                        order.ItemDatailsList.Add(orderDetails);
                        detailID++;

                    }

                }
                //添加到总订单
                orderList.Add(order);
            }

            //构造xml, 用于插入数据库
            var orderXml = BuildOrderXML(orderList);
            //入库
            int result = shopCartService.InsertOrder(orderXml);

            return result > 0 ? "Ok" : "入库异常" + orderXml;
        }


        /// <summary>
        /// 构造订单Xml
        /// </summary>
        /// <param name="OrderList"></param>
        /// <returns></returns>
        private string BuildOrderXML(List<ItemOrderData> OrderList)
        {
            var orderXML = new XElement("Orders");
            foreach (var order in OrderList)
            {
                var orderNode = new XElement("Order");
                orderXML.Add(orderNode);
                orderNode.Add(new XElement("OrderId", order.OrderId));
                orderNode.Add(new XElement("LoginId", order.LoginId));
                orderNode.Add(new XElement("TotalMoney", order.TotalMoney));
                orderNode.Add(new XElement("FactMoney", order.FactMoney));
                orderNode.Add(new XElement("Discount", order.Discount));
                orderNode.Add(new XElement("VendorNumber", order.VendorNumber));
                orderNode.Add(new XElement("ShippingType", order.ShippingType));
                orderNode.Add(new XElement("OrderStatus", order.OrderStatus));
                orderNode.Add(new XElement("PaymentType", order.PaymentType));
                orderNode.Add(new XElement("Address", order.Address));

                var itemsNode = new XElement("Items");
                orderNode.Add(itemsNode);
                foreach (var item in order.ItemDatailsList)
                {
                    var itemNode = new XElement("Item");
                    itemsNode.Add(itemNode);
                    itemNode.Add(new XElement("OrderId", item.OrderId));
                    itemNode.Add(new XElement("OrderDetailId", item.OrderDetailId));
                    itemNode.Add(new XElement("QRCode", item.QRCode));
                    itemNode.Add(new XElement("ItemNumber", item.ItemNumber));
                    itemNode.Add(new XElement("Unit", item.Unit));
                    itemNode.Add(new XElement("Count", item.Count));
                    itemNode.Add(new XElement("UnitPrice", item.UnitPrice));
                    itemNode.Add(new XElement("ProductID", item.ProductID));
                }
            }
            return new XDocument(orderXML).ToString();
        }

    }


}
